﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TextTemplating;

namespace ABPGenerator.Db
{
    class Manager
    {
        //定义一个 block 块，主要是应用在批量生产中
        public struct Block
        {
            public String Name;
            public int Start, Length;
        }

        public List<Block> blocks = new List<Block>();
        public Block currentBlock;
        public Block footerBlock = new Block();
        public Block headerBlock = new Block();
        public ITextTemplatingEngineHost host;
        public ManagementStrategy strategy;
        public StringBuilder template;
        public String OutputPath { get; set; }
        //构造函数，包含 host主机，模板，输出路径，创建管理策略
        public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader)
        {
            this.host = host;
            this.template = template;
            OutputPath = String.Empty;
            strategy = ManagementStrategy.Create(host);
        }
        //开辟一个 block 块
        public void StartBlock(String name)
        {
            currentBlock = new Block { Name = name, Start = template.Length };
        }

        public void StartFooter()
        {
            footerBlock.Start = template.Length;
        }

        public void EndFooter()
        {
            footerBlock.Length = template.Length - footerBlock.Start;
        }

        public void StartHeader()
        {
            headerBlock.Start = template.Length;
        }

        public void EndHeader()
        {
            headerBlock.Length = template.Length - headerBlock.Start;
        }

        public void EndBlock()
        {
            currentBlock.Length = template.Length - currentBlock.Start;
            blocks.Add(currentBlock);
        }
        //定义进程，用来将所有的 blocks 块执行出来
        public void Process(bool split)
        {
            String header = template.ToString(headerBlock.Start, headerBlock.Length);
            String footer = template.ToString(footerBlock.Start, footerBlock.Length);
            blocks.Reverse();
            foreach (Block block in blocks)
            {//遍历
             //输出文件
                String fileName = Path.Combine(OutputPath, block.Name);
                if (split)
                {
                    String content = header + template.ToString(block.Start, block.Length) + footer;
                    strategy.CreateFile(fileName, content);
                    template.Remove(block.Start, block.Length);
                }
                else
                {
                    strategy.DeleteFile(fileName);
                }
            }
        }
    }
   
}
